package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.StringUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/4 19:00
 */
@Slf4j
@Service
public class VideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Autowired
    private PicUploadService picUploadService;


    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;


    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private QuanZiService quanZiService;

    /**
     * 小视频上传：
     *
     * @param multipartFilePic   封面
     * @param multipartFileVideo 视频
     * @return
     */
    public Boolean saveSmallVideo(MultipartFile multipartFilePic, MultipartFile multipartFileVideo) {
        Video video = new Video();

        User user = UserThreadLocal.get();
        video.setUserId(user.getId());
        video.setSeeType(1);
        StorePath storePath = null;

        try {
            //上传封面图片到oss
            PicUploadResult upload = picUploadService.upload(multipartFilePic);
            video.setPicUrl(upload.getName());

            //上传小视频到FastDFS
            storePath = this.storageClient.uploadFile(multipartFileVideo.getInputStream(),
                    multipartFileVideo.getSize(),
                    StrUtil.subAfter(multipartFileVideo.getOriginalFilename(), ".", true),
                    null);
            String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
            if (!StrUtil.isNotEmpty(videoUrl)) {
                return false;
            }
            video.setVideoUrl(videoUrl);
            String s = videoApi.saveVideo(video);
            if (StrUtil.isNotEmpty(s)) {
                return true;
            }
        } catch (Exception e) {
            log.error("文件上传失败！ user" + user, "file" + multipartFileVideo.getOriginalFilename(), e);
        }
        return false;
    }


    /**
     * 查询小视频列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findVideoList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        //调用VideoApi查询：
        PageInfo<Video> videoList = videoApi.findVideoList(user.getId(), page, pageSize);
        List<Video> records = videoList.getRecords();

        //封装videoVo
        List<Object> ids = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(ids);

        //构建userId  与 userInfo的key -value关系：
        Map<Long, UserInfo> idToUserInfoMap = new HashMap<>();
        for (UserInfo userInfo : userInfos) {
            idToUserInfoMap.put(userInfo.getUserId(), userInfo);
        }

        List<VideoVo> videoVos = new ArrayList<>();
        VideoVo videoVo;
        for (Video record : records) {
            videoVo = new VideoVo();
            videoVo.setId(record.getId().toHexString());
            videoVo.setCover(record.getPicUrl());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setSignature("哈哈哈哈");
            videoVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(videoVo.getId())));
            videoVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(), videoVo.getId()) ? 1 : 0);
            videoVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentCount(videoVo.getId()))); //评论数
            videoVo.setHasFocus(videoApi.isFollowUser(user.getId(), videoVo.getUserId()) ? 1 : 0);
            videoVo.setUserId(record.getUserId());

            //用户信息：
            videoVo.setAvatar(idToUserInfoMap.get(videoVo.getUserId()).getLogo());
            videoVo.setNickname(idToUserInfoMap.get(videoVo.getUserId()).getNickName());

            videoVos.add(videoVo);
        }
        pageResult.setItems(videoVos);
        return pageResult;
    }


    /**
     * 小视频点赞
     *
     * @param videoId
     * @return
     */
    public Long likeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean aBoolean = quanZiApi.likeComment(user.getId(), videoId);
        if (aBoolean) {
            //查询点赞数量返回：
            return quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }


    /**
     * 小视频取消点赞
     *
     * @param videoId
     * @return
     */
    public Long disLikeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean aBoolean = quanZiApi.disLikeComment(user.getId(), videoId);
        if (aBoolean) {
            //查询点赞数量返回：
            return quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    /**
     * 查询小视频列表
     *
     * @param videoId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {

        return quanZiService.queryCommentList(videoId, page, pageSize);
    }

    /**
     * 发表小视频的评论
     *
     * @param videoId
     * @param content
     * @return
     */
    public Boolean saveComment(String videoId, String content) {
        return quanZiService.saveComments(videoId, content);
    }

    /**
     * 关注用户：
     *
     * @param followUserId
     * @return
     */
    public Boolean followUser(Long followUserId) {
        User user = UserThreadLocal.get();

        return videoApi.followUser(user.getId(), followUserId);
    }

    /**
     * 取消关注该用户
     *
     * @param followUserId
     * @return
     */
    public Boolean unfollowUser(Long followUserId) {

        User user = UserThreadLocal.get();

        return videoApi.unFollowUser(user.getId(), followUserId);
    }
}
